package com.course.server.service;

import cn.hutool.core.util.StrUtil;
import com.course.server.dto.PageDto;
import com.course.server.dto.SectionDto;
import com.course.server.entity.Section;
import com.course.server.entity.SectionExample;
import com.course.server.enums.SectionChargeEnum;
import com.course.server.mapper.SectionMapper;
import com.course.server.util.CopyUtil;
import com.course.server.util.UuidUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author: Durian
 * @date: 2021/5/1 20:51
 */
@Service
public class SectionService {

    @Resource
    private SectionMapper sectionMapper;
    @Resource
    private CourseService courseService;

    public PageDto<SectionDto> list(int page, int size, String chapterId, String courseId) {
        PageHelper.startPage(page, size);
        SectionExample example = new SectionExample();
        SectionExample.Criteria criteria = example.createCriteria();
        if (StrUtil.isNotBlank(chapterId)) {
            criteria.andChapterIdEqualTo(chapterId);
        }
        if (StrUtil.isNotBlank(courseId)) {
            criteria.andCourseIdEqualTo(courseId);
        }

        example.setOrderByClause("sort asc");
        List<Section> sections = sectionMapper.selectByExample(example);
        PageInfo<Section> pageInfo = new PageInfo<>(sections);

        List<SectionDto> sectionDtos = CopyUtil.copyList(sections, SectionDto.class);
        PageDto<SectionDto> pageDto = new PageDto<>();
        pageDto.setPage(page);
        pageDto.setSize(size);
        pageDto.setList(sectionDtos);
        pageDto.setTotal(pageInfo.getTotal());
        return pageDto;
    }

    @Transactional(rollbackFor = {Exception.class})
    public void save(SectionDto sectionDto) {
        Section section = new Section();
        BeanUtils.copyProperties(sectionDto, section);
        if (StrUtil.isBlank(sectionDto.getId())) {
            insert(section);
        } else {
            update(section);
        }
        courseService.updateTime(section.getCourseId());
    }

    public void delete(String id) {
        sectionMapper.deleteByPrimaryKey(id);
    }

    private void insert(Section section) {
        section.setId(UuidUtils.getShortUuid());
        section.setCreatedAt(LocalDateTime.now());
        section.setUpdatedAt(LocalDateTime.now());
        section.setCharge(String.valueOf(SectionChargeEnum.CHARGE.getCode()));
        sectionMapper.insert(section);
    }

    private void update(Section section) {
        section.setUpdatedAt(LocalDateTime.now());
        sectionMapper.updateByPrimaryKeySelective(section);
    }

}
